package org.ruanjj.multithread.JUC;

import java.util.concurrent.atomic.AtomicReference;

public class SpinLockDemo {
   AtomicReference<Thread> atomicReference =  new AtomicReference<Thread>();
    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(()->{
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            spinLockDemo.printEvenNumber();
        },"t1").start();

        new Thread(()->{
            spinLockDemo.printEvenNumber();
        },"t2").start();

    }

    public void lock(){
        Thread thread = Thread.currentThread();
        while(!atomicReference.compareAndSet(null,thread)){

        }
    }

    public void unlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
    }

    public void printEvenNumber(){
        lock();
        for (int i = 0; i < 50; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            if(i%2 == 0){
                System.out.println(Thread.currentThread().getName()+"打印"+i);
            }
        }
        unlock();
    }
}
